package com.itstu.netty;


import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @author lz
 */
@Configuration
@ChannelHandler.Sharable
public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public Map<String, Channel> cmap = new HashMap<>();

    private final String USER = "user";


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接，通道开启！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));
        Map map = JSON.parseObject(msg.text(), Map.class);
        String type = map.get("type").toString();
        switch (type) {
            case "login":
                websocketLogin(map, ctx);
                break;
            case "message":
                websocketMessage(map, ctx);
                break;
            case "video":
                websocketVideo(map, ctx);
                break;
            case "videoAccept":
                websocketVideoAccept(map, ctx);
                break;
            default:
                break;
        }
    }

    private void sendMessage(ChannelHandlerContext ctx) throws InterruptedException {
        String message = "我是服务器，你好呀";
        ctx.writeAndFlush(new TextWebSocketFrame("hello"));
    }


    private void websocketLogin(Map map, ChannelHandlerContext ctx) {
        String uid = map.get("uid").toString();
        cmap.put(USER + uid, ctx.channel());
        System.out.println("用户uid:" + uid + "--登录");
    }

    private void websocketMessage(Map map, ChannelHandlerContext ctx) {
        String to = map.get("to").toString();
        if (cmap.containsKey(USER + to)) {
            HashMap<String, Object> response = new HashMap<>(2);
            Channel channel = cmap.get(USER + to);
            response.put("type", "message");
            response.put("uuid", UUID.randomUUID().toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)));
        }
    }

    /**
     * 视频请求
     */
    private void websocketVideo(Map map, ChannelHandlerContext ctx) {
        String to = map.get("to").toString();
        if (cmap.containsKey(USER + to)) {
            HashMap<String, Object> response = new HashMap<>(3);
            Channel channel = cmap.get(USER + to);
            response.put("type", "video");
            response.put("uuid", UUID.randomUUID().toString());
            response.put("from", map.get("uid").toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)));
        }
    }

    /**
     * 接受视频请求
     */
    private void websocketVideoAccept(Map map, ChannelHandlerContext ctx) {
        System.out.println("进入websocketVideoAccept");
        String to = map.get("to").toString();
        if (cmap.containsKey(USER + to)) {
            HashMap<String, Object> response = new HashMap<>(3);
            Channel channel = cmap.get(USER + to);
            response.put("type", "videoAccept");
            response.put("uuid", UUID.randomUUID().toString());
            response.put("from", map.get("uid").toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)));
        }
    }

}